package com.cloudfun.campusshare.configuration.jpa.restriction.support;


import com.cloudfun.campusshare.configuration.jpa.restriction.PredicateSingleValueSupport;
import com.cloudfun.campusshare.configuration.jpa.util.MatchValue;
import com.cloudfun.campusshare.configuration.jpa.util.RestrictionNames;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;

/**
 * @author 王溪源
 * @ClassName: EqRestriction
 * @Description: TODO
 * @Date 2020/8/10 11:01
 **/
public class EqRestriction extends PredicateSingleValueSupport {
    @Override
    public Predicate build(Path<?> path, Object value, CriteriaBuilder builder) {
        return value == null ? builder.isNull (path) : builder.equal (path, value);
    }

    @Override
    public MatchValue getMatchValue(String matchValue, Class<?> propertyType) {
        MatchValue matchValueModel = super.getMatchValue (matchValue, propertyType);
        for (int i = 0; i < matchValueModel.getValues ().size (); i++) {
            Object value = matchValueModel.getValues ().get (i);
            if (value instanceof String && StringUtils.equals (value.toString (), "null")) {
                matchValueModel.getValues ().remove (i);
                matchValueModel.getValues ().add (i, null);
            }
        }
        return matchValueModel;
    }

    @Override
    public String getRestrictionName() {
        return RestrictionNames.EQ;
    }
}
